from pathlib import Path
import yagmail
from common.log import logger
from config.config import LOG_PATH


class EmailOperate(object):
    def __init__(self):
        self.__username = "rainbow_twc@163.com"
        self.__password = "FIGHTING0829"
        self.__host = "smtp.163.com"
        try:
            self.email = yagmail.SMTP(user=self.__username, password=self.__password, host=self.__host)
        except yagmail.error as e:
            logger.error(f"{e}")
            logger.error(f"Failed to initialize yagmail instance")

    def send_email(self, receiver: str, subject: str, contents: str, attachments=None):
        """
        可发送带有附件的邮件
        :param receiver: 收件人邮箱
        :param subject: 邮件主题
        :param contents: 邮件正文
        :param attachments: 邮件附件，可以是一个或多个，即str类型或元素是str类型的列表
        :return:
        """
        try:
            self.email.send(receiver, subject, contents, attachments)
            result = {"code":"000", "message":"发送邮件成功", "data":[]}
        except yagmail.error as e:
            logger.error(f"{e}")
            logger.error(f"Failed to send email")
            result = {"code": "500", "message": "发送邮件失败", "data": []}
        return result


if __name__ == "__main__":
    email = EmailOperate()
    email.send_email("tianwencheng829@gmail.com", u"测试EmailOperate类是否正常实现发送邮件功能", "google邮箱比163邮箱好用", f"{Path(LOG_PATH)/'interface_test.log'}")